console.log(window);
console.log(chrome.cookies);
var tabId = "";
var imgUrl = [];
var timer = null;
$(document).ready(function () {
  loadCachedParams();
  $(".getImg").click(function () {
    console.log(123321);
    var key = $("#key").val();
    var type = $("#class").val();
    var selectImg = $("#selectImg").val();
    cacheParams(key, type, selectImg);
    getImg(key, type, selectImg);
  });
  $(".autoGetImg").click(function () {
    console.log("自动获取");
    var key = $("#key").val();
    var type = $("#class").val();
    var selectImg = $("#selectImg").val();
    timer = setInterval(function () {
      autoScroll(key, type, selectImg);
    }, 2000);
  });
  $(".stopAutoGetImg").click(function () {
    if (timer) {
      clearInterval(timer);
    }
  });
  $(".downImg").click(function () {
    console.log("下载");
    // getImg()
    var time = getNowTime();
    console.log(time);
    for (var i = 0; i < imgUrl.length; i++) {
      downloadIamge(imgUrl[i], "img" + time);
    }
  });
});

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  var tab = tabs[0];
  //获取当前tab
  console.log(tab);
  console.log(tab.id);
  tabId = tab.id;
  console.log(tab.title);
  console.log(tab.url);
  console.log(tab.favIconUrl);
  console.log(tab.width);
  $(".title").text(tab.title);
  $(".url").text(tab.url);
  $(".favIconUrl img").attr("src", tab.favIconUrl);
  $(".width").text(tab.width);

  chrome.tabs.sendMessage(tab.id, { greeting: "scroll" }, function (response) {
    if (chrome.runtime.lastError) {
      console.log("Error: ", chrome.runtime.lastError.message);
      return;
    }
    console.log("scroll", response); // 向content-script.js发送请求信息,拿到了！
    var img = "";
    imgUrl = response;
    imgUrl = [...new Set(imgUrl)];
    for (var i = 0; i < imgUrl.length; i++) {
      img +=
        "<div class='masonry-item'><a href='" +
        imgUrl[i] +
        "' target='_blank'><img src='" +
        imgUrl[i] +
        "' onerror='this.parentNode.remove()'></a></div>";
    }
    $(".masonry-container").html(img);
    // 为所有图片添加加载成功和错误处理
    $(".masonry-container img")
      .on("load", function () {
        // 图片加载成功，确保显示
        $(this).css("visibility", "visible");
      })
      .on("error", function () {
        // 图片加载失败，移除整个项
        $(this).parent().remove();
      });
  });
  chrome.tabs.sendMessage(tab.id, { greeting: "html" }, function (response) {
    if (chrome.runtime.lastError) {
      console.log("Error: ", chrome.runtime.lastError.message);
      return;
    }
    console.log("html", response); // 向content-script.js发送请求信息,拿到了！
  });
  chrome.tabs.sendMessage(tab.id, { greeting: "imglist" }, function (response) {
    if (chrome.runtime.lastError) {
      console.log("Error: ", chrome.runtime.lastError.message);
      return;
    }
    console.log("imglist", response); // 向content-script.js发送请求信息,拿到了！
    var img = "";
    imgUrl = response;
    imgUrl = [...new Set(imgUrl)];
    for (var i = 0; i < imgUrl.length; i++) {
      img +=
        "<div class='masonry-item'><a href='" +
        imgUrl[i] +
        "' target='_blank'><img src='" +
        imgUrl[i] +
        "' onerror='this.parentNode.remove()'></a></div>";
    }
    $(".masonry-container").html(img);
    // 为所有图片添加加载成功和错误处理
    $(".masonry-container img")
      .on("load", function () {
        // 图片加载成功，确保显示
        $(this).css("visibility", "visible");
      })
      .on("error", function () {
        // 图片加载失败，移除整个项
        $(this).parent().remove();
      });
  });
  chrome.tabs.sendMessage(tab.id, { greeting: "mp4" }, function (response) {
    if (chrome.runtime.lastError) {
      console.log("Error: ", chrome.runtime.lastError.message);
      return;
    }
    console.log("mp4", response); // 向content-script.js发送请求信息,拿到了！
  });
});

// ... existing code ...

// chrome.extension.getViews({type:"notification"}).forEach(function(win) {
// 	win.doOtherThing();
// });
// chrome.tabs.sendRequest(tab.id, { action: "GetBaiduKeyWord" }, function (response) {
// 	console.log(response)
// 	// alert(response.kw);
// });
// $('.box').each(function(k){
// 	console.log(this,k)
// 	if(k==0){
// 		this.innerText=tab.title
// 	}

// })
//向tab发送请求
//chrome.tabs.sendRequest(tab.id, { action: "GetBaiduKeyWord" }, function (response) {
//	alert(response.kw);
//});

// 获取缓存参数
function loadCachedParams() {
  try {
    var cachedParams = localStorage.getItem("imageDownloaderParams");
    if (cachedParams) {
      var params = JSON.parse(cachedParams);
      $("#key").val(params.key || "");
      $("#class").val(params.type || "");
      $("#selectImg").val(params.selectImg || "");
    }
  } catch (e) {
    console.error("读取缓存参数失败:", e);
  }
} // 设置缓存参数
function cacheParams(key, type, selectImg) {
  try {
    var params = {
      key: key,
      type: type,
      selectImg: selectImg,
    };
    localStorage.setItem("imageDownloaderParams", JSON.stringify(params));
  } catch (e) {
    console.error("缓存参数失败:", e);
  }
}

//获取时间函数
function getNowTime() {
  var now = new Date();
  var time =
    now.getFullYear() +
    "-" +
    (now.getMonth() + 1 < 10 ? "0" : "") +
    (now.getMonth() + 1) +
    "-" +
    (now.getDate() < 10 ? "0" : "") +
    now.getDate() +
    "" +
    " " +
    (now.getHours() < 10 ? "0" + now.getHours() : now.getHours()) +
    ":" +
    (now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes()) +
    ":" +
    (now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds());
  return time;
}
function autoScroll(key, type, selectImg) {
  console.log(tabId, key, type);
  chrome.tabs.sendMessage(
    tabId,
    { greeting: "scroll", type: type, key: key, selectImg: selectImg },
    function (response) {
      if (chrome.runtime.lastError) {
        console.log("Error: ", chrome.runtime.lastError.message);
        return;
      }
      console.log("scroll", response); // 向content-script.js发送请求信息,拿到了！
      var img = "";
      imgUrl = response;
      imgUrl = [...new Set(imgUrl)];
      for (var i = 0; i < imgUrl.length; i++) {
        img +=
          "<div class='masonry-item'><a href='" +
          imgUrl[i] +
          "' target='_blank'><img src='" +
          imgUrl[i] +
          "' onerror='this.parentNode.remove()'></a></div>";
      }
      $(".masonry-container").html(img);
      // 为所有图片添加加载成功和错误处理
      $(".masonry-container img")
        .on("load", function () {
          // 图片加载成功，确保显示
          $(this).css("visibility", "visible");
        })
        .on("error", function () {
          // 图片加载失败，移除整个项
          $(this).parent().remove();
        });
    }
  );
}

function getImg(key, type, selectImg) {
  console.log(tabId, key, type);
  chrome.tabs.sendMessage(
    tabId,
    { greeting: "imglist", type: type, key: key, selectImg: selectImg },
    function (response) {
      if (chrome.runtime.lastError) {
        console.log("Error: ", chrome.runtime.lastError.message);
        return;
      }
      console.log("imglist", response); // 向content-script.js发送请求信息,拿到了！
      var img = "";
      imgUrl = response;
      imgUrl = [...new Set(imgUrl)];
      for (var i = 0; i < imgUrl.length; i++) {
        img +=
          "<div class='masonry-item'><a href='" +
          imgUrl[i] +
          "' target='_blank'><img src='" +
          imgUrl[i] +
          "' onerror='this.parentNode.remove()'></a></div>";
      }
      $(".masonry-container").html(img);
      // 为所有图片添加加载成功和错误处理
      $(".masonry-container img")
        .on("load", function () {
          // 图片加载成功，确保显示
          $(this).css("visibility", "visible");
        })
        .on("error", function () {
          // 图片加载失败，移除整个项
          $(this).parent().remove();
        });
    }
  );
}

function downloadIamge(imgsrc, name) {
  //下载图片地址和图片名
  let image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    let a = document.createElement("a"); // 生成一个a元素
    let event = new MouseEvent("click"); // 创建一个单击事件
    a.download = name || "photo"; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  };
  image.src = imgsrc;
}
// 创建一个简单的文字通知：
// var notification = webkitNotifications.createNotification(
// 	'hello_extensions.png',  // icon url - can be relative
// 	'Hello!',  // notification title
// 	'Lorem ipsum...'  // notification body text
//   );

// 或者创建一个 HTML 通知：
//   var notification = webkitNotifications.createHTMLNotification(
// 	'notification.html'  // html url - can be relative
//   );
// 显示通知
//   notification.show();
